package yang_exp.concurrent;

import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


/* 
    最安全的实现方式：volatile + blockingQueue

    想要实现随时通过设置的标志位叫停，因此标志位要保证在主线程修改后马上
    被其他线程察觉，并停止当前任务
*/
public class ProductorAndComsumer3 {

    // 刚开头允许工作
    private static volatile boolean FLAG = true;

    static class MyResource {
        private BlockingQueue<String> production;
        private static final int CAPACITY = 5;
        private volatile AtomicInteger count; // 作为资源的名称

        public MyResource(BlockingQueue<String> production) {
            this.production = production;
            count = new AtomicInteger(0);
        }

        public void product() throws InterruptedException {
            String pro = null;
            boolean success = false;
            while (FLAG) {
                // 实际工作
                pro = count.incrementAndGet() + "";
                // 因为资源是每1秒生产一个，因此两秒还没有，就认为已经工作结束
                success = production.offer(pro, 2, TimeUnit.SECONDS);
                if (success) {
                    System.out.println("生产者" + Thread.currentThread().getName() + "生产了" + pro);
                } else {
                    System.out.println("生产者" + Thread.currentThread().getName() + "生产" + pro + "失败");

                }
                TimeUnit.SECONDS.sleep(1);
            }

            System.out.println("工程停止");
        }

        public void consume() throws InterruptedException {
            while (FLAG) {
                String res = production.poll(2, TimeUnit.SECONDS);
                if (res == null || "".equalsIgnoreCase(res)) {
                    FLAG = false;
                    System.out.println("消费失败");
                } else {
                    System.out.println(Thread.currentThread().getName() + "消费了" + res);
                    TimeUnit.SECONDS.sleep(1);
                }
            }
            System.out.println("工程停止");
        }

        public void stop() {
            FLAG = false;
        }
    }

    public static void main(String[] args) {
        MyResource resource = new MyResource(new LinkedBlockingQueue<>());
        while (FLAG) {
            new Thread(() -> {
                try {
                    resource.product();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();

            new Thread(() -> {
                try {
                    resource.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            try {
                TimeUnit.SECONDS.sleep(10);
                System.out.println("老板叫停");
                resource.stop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
